package com.yun.util.yun.utils.file;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.*;

public class SysFileUtil {

    /**
     * <p>Method:saveImpExcel</p>
     * <p>Description:保存文件，返回文件路径</p>
     */

    private static final Logger logger= LoggerFactory.getLogger(SysFileUtil.class);

    public static String saveImpExcel(String dir,String excelName, InputStream is) throws IOException {
        File diry = new File(dir);
        if(!diry.exists()) {
            diry.mkdirs();
        }        
        File file = new File(dir, excelName);
        FileOutputStream stream = new FileOutputStream(file);
        FileCopyUtils.copy(is, stream);
        return file.getPath();
    }

    /**
     * <p>Method:getFileName</p>
     * <p>Description:根据文件路径，获取文件名</p>
     */
    public static String getFileName(String fileFullPath) {
        if (fileFullPath.lastIndexOf("/") > fileFullPath.lastIndexOf("\\")) {
            return fileFullPath.substring(fileFullPath.lastIndexOf("/"));
        }
        return fileFullPath.substring(fileFullPath.lastIndexOf("\\"));
    }

    public static Workbook getWorkBookFile(String resultFile) throws FileNotFoundException, IOException {
        File file = new File(resultFile);
        if (!file.exists()) {
            return null;
        }
        if (resultFile.toLowerCase().endsWith(".xls")) {
            return new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(file)));
        } else if (resultFile.toLowerCase().endsWith(".xlsx")) {
            return new XSSFWorkbook(new FileInputStream(file));
        }
        return null;
    }

    public static String readToString(String fileName) throws IOException {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in =null;
        try {
            in = new FileInputStream(file);
            in.read(filecontent);
        } catch (FileNotFoundException e) {
            logger.error("",e);
        } catch (IOException e) {
            logger.error("",e);
        }
        finally {
            in.close();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            logger.error("The OS does not support " + encoding);
            logger.error("",e);
            return null;
        }
    }

    public static ByteArrayOutputStream getOutputStream(String filePath) {
        ByteArrayOutputStream bos=null;
        BufferedInputStream in=null;
        try{
            File file=new File(filePath);
            if(!file.exists()){
                throw new FileNotFoundException("file not exists");
            }
            bos=new ByteArrayOutputStream((int)file.length());
            in=new BufferedInputStream(new FileInputStream(file));
            int buf_size=1024;
            byte[] buffer=new byte[buf_size];
            int len=0;
            while(-1 != (len=in.read(buffer,0,buf_size))){
                bos.write(buffer,0,len);
            }
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally{
            try{
                if(in!=null){
                    in.close();
                }
                if(bos!=null){
                    bos.close();
                }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        return bos;
    }
}
